(function () {

	//获取占比划分数据 服务器分页
    divideScaleData = {};
	divideScaleData.contractId=jQuery('#contractId').val();
    
    jQuery(document).ready(function () {
    	serverScaleTable = jQuery('#resultScaleTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "iDisplayLength": 5,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/contract/getDivideScale',
                "data": function (d) {
                    return $.extend({}, d, divideScaleData);
                }
            },
            columns: [
                {
                	data: null
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchildScale">';
    	            	return operate;
    	            }   
                },
                {
                    data: 'functionary'
                },
                {
                	data: 'belongArea'
                },
                {
                    data: 'scaleDivide'
                },
                {
                    data: 'percent'
                },
                {
                    data: 'memo',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 20) ? '<font title="'+data+'">'+data.substring(0,20)+'...'+'</font>' : data;
						}
					}
                }
                ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    	
    	//删除项目合同占比划分
    	jQuery('.delScaleBtn').on('click', function () {
    		   var selects=getSelect("#resultScaleTable",1);
    		   var url=window.rootPath+"/ui/contract/deleteDivideScale";
    		   var contractId = jQuery("#contractId").val(); 
    		   var totalSum = jQuery("#totalSum").val();
    		   $("#checkAllScale").prop("checked", false);
    		   delSelect(selects,url,serverScaleTable);
    		   var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractId + '&totalSum=' + totalSum;
    		   jQuery.ajax({
               	type : 'get',
               	url : encodeURI(urlxy),
               	dataType : 'json',
               	contentType : 'application/json;charset=utf-8',
               	success : function(data) {
               		if(data==0){
               			alert("合同金额与细目的总金额相同！");
               		} else if(data==1){
               			alert("合同金额小于细目的总金额！");
               		} else if(data==2){
               			alert("合同金额大于细目的总金额！");
               		}
               	}
               });
    		});
    	
        //占比新建弹窗显示,数据清空,若合同未保存则保存合同后再新建
    	jQuery('.addScaleBtn').on('click', function () {
    		var contractId=jQuery("#contractId").val();
            if(contractId == ""){
            	if (confirm("当前合同还未保存，是否保存？")) {
            		saveContract("addScaleBtn");
            	}
            }else{
            	showDivideScaleModal();
            }
    	});
        
    	//占比编辑弹窗显示
    	jQuery('.editScaleBtn').on('click', function () {
    	       var selects=getSelect("#resultScaleTable",1);
    		   if(selects.length>1){
    			   $.springLemonDialog({
    			         content: '只能编辑一条记录',// 确认文本
    			         clickButton: function (sender, modal, index) {// 按钮事件处理
    			             $(this).closeDialog(modal);
    			         }
    			   }); 
    		   }
    		   else if(selects.length==0){
    			   $.springLemonDialog({
    			         content: '请选择要编辑的记录',// 确认文本
    			         clickButton: function (sender, modal, index) {// 按钮事件处理
    			             $(this).closeDialog(modal);
    			         }
    			   }); 
    		   }else if(selects.length==1){
    			   	jQuery('#divideScaleId').val(selects[0].id);
    			   	jQuery("#functionary").select2().val(selects[0].functionary).trigger("change");
    	        	jQuery('#divideScaleBelongArea').val(selects[0].belongArea);
    	        	jQuery('#oldScaleDivide').val(selects[0].scaleDivide);
    	     		jQuery('#scaleDivide').val(selects[0].scaleDivide);
    	     		jQuery('#percent').val(selects[0].percent);
    	     		jQuery('#divideScaleMemo').val(selects[0].memo);
    	    		jQuery('#divideScaleModal').modal('show');
    		   }
    		   
    		});
        
        //保存
    	var $btn = jQuery('.saveScaleBtn').on('click', function () {
    		if(jQuery("#divideScaleAtrrForm") && !jQuery("#divideScaleAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
                return;
            };
            //saveContract("saveScaleBtn");
            saveScaleDivide();
    	});
    	
    	/**
    	 * 保存项目合同
    	 */
        var saveContract = function(state) {
        	var signedDate = jQuery('#signedDate').val();
         	var scheduleDate = jQuery('#scheduleDate').val();
         	var giveOutDate = jQuery('#giveOutDate').val();
     		var operatDate = jQuery('#operatDate').val();
     		if (signedDate==""||scheduleDate==""||giveOutDate==""||operatDate==""){
     			message("请将页面上所有日期信息完善，保存后还可进行编辑。");
     			return ;
     		}
      	    var isId=jQuery("#contractId").val();
      	    var contractcreateTime=jQuery("#createTime").val();
    	    var createTime=new Date(contractcreateTime).getTime();
      	    var supplierCode = jQuery('#supplierCode').val();
      		var demanderCode = jQuery('#demanderCode').val();
      		var contractType = jQuery('#contractType').val();
      		var totalSum = jQuery('#totalSum').val();
      		var stop = jQuery('#stop').val();
      		var freightCharge = jQuery('#freightCharge').val();
      		var projectName = jQuery('#projectName').val();
      	 	var payType = jQuery('#payType').val();
      	 	var guaranteePeriod = jQuery('#guaranteePeriod').val();
      	 	var breakDuty = jQuery('#breakDuty').val();
      	 	var customerId = jQuery("#customerId").val();
      		var orderUnit = jQuery('#orderUnit').val();
      	 	var orderDelegate = jQuery('#orderDelegate').val();
      		var orderPhone = jQuery('#orderPhone').val();
      		var industryInfo = jQuery('#industryInfo').val();
      		var orderAddress = jQuery('#orderAddress').val();
      		var orderZip = jQuery('#orderZip').val();
      		var orderArea = jQuery('#orderArea').val();
      		var invoiceBank = jQuery("#invoiceBank").val();
      		var bankAccount = jQuery("#bankAccount").val();
      		var taxNumber = jQuery("#taxNumber").val();
      		var invoiceAddress = jQuery("#invoiceAddress").val();
      		var postUnit = jQuery('#postUnit').val();
      	 	var postDelegate = jQuery('#postDelegate').val();
      		var postPhone = jQuery('#postPhone').val();
      		var postAddress = jQuery('#postAddress').val();
      		var postZip = jQuery('#postZip').val();
      		var dutyArea = jQuery('#dutyArea').val();
      		var dutyOfficer = jQuery('#dutyOfficer').val();
      		var southNorthArea = jQuery('#southNorthArea').val();
      		var belongArea = jQuery('#belongArea').val();
      		var checkKind = jQuery('#checkKind').val();
      		var productKind = jQuery('#productKind').val();
      		var signOfficer = jQuery('#signOfficer').val();
      		var repairOfficer = jQuery('#repairOfficer').val();
      		var quotationOfficer = jQuery('#quotationOfficer').val();
      		var operatDepartment = jQuery('#operatDepartment').val();
      		var operator = jQuery('#operator').val();
      		var memo = jQuery('#memo').val();
      		var state = jQuery('#state').val();
      		var cstate = jQuery('#cstate').val();
      		if(isId == ""){// 新增合同
	      		var d = {
	     				"user":{"id":$("#userId").val()},
	                	"supplierCode": supplierCode,
	                	"demanderCode": demanderCode,
	                	"contractType": contractType,
	                    "totalSum": totalSum,
	                    "signedDate": signedDate,
	                    "scheduleDate": scheduleDate,
	                    "giveOutDate": giveOutDate,
	                    "stop": stop,
	                    "freightCharge": freightCharge,
	                    "projectName": projectName,
	                    "payType": payType,
	                    "guaranteePeriod": guaranteePeriod,
	                    "breakDuty": breakDuty,
	                    "customerId": customerId,
	                    "orderUnit": orderUnit,
	                    "orderDelegate": orderDelegate,
	                    "orderPhone": orderPhone,
	                    "industryInfo": industryInfo,
	                    "orderAddress": orderAddress,
	                    "orderZip": orderZip,
	                    "orderArea": orderArea,
	                    "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
	                    "postUnit": postUnit,
	                    "postDelegate": postDelegate,
	                    "postPhone": postPhone,
	                    "postAddress": postAddress,
	                    "postZip": postZip,
	                    "dutyArea": dutyArea,
	                    "dutyOfficer": dutyOfficer,
	                    "southNorthArea": southNorthArea,
	                    "belongArea": belongArea,
	                    "checkKind": checkKind,
	                    "productKind": productKind,
	                    "signOfficer": signOfficer,
	                    "repairOfficer": repairOfficer,
	                    "quotationOfficer": quotationOfficer,
	                    "operatDepartment": operatDepartment,
	                    "operator": operator,
	                    "operatDate": operatDate,
	                    "memo": memo,
	                    "state": state,
	                    "cstate": cstate,
	            };
      		}else{
      			var d = {
      					"id": isId,
  	        			"createTime": createTime,
	                	"supplierCode": supplierCode,
	                	"demanderCode": demanderCode,
	                	"contractType": contractType,
	                    "totalSum": totalSum,
	                    "signedDate": signedDate,
	                    "scheduleDate": scheduleDate,
	                    "giveOutDate": giveOutDate,
	                    "stop": stop,
	                    "freightCharge": freightCharge,
	                    "projectName": projectName,
	                    "payType": payType,
	                    "guaranteePeriod": guaranteePeriod,
	                    "breakDuty": breakDuty,
	                    "customerId": customerId,
	                    "orderUnit": orderUnit,
	                    "orderDelegate": orderDelegate,
	                    "orderPhone": orderPhone,
	                    "industryInfo": industryInfo,
	                    "orderAddress": orderAddress,
	                    "orderZip": orderZip,
	                    "orderArea": orderArea,
	                    "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
	                    "postUnit": postUnit,
	                    "postDelegate": postDelegate,
	                    "postPhone": postPhone,
	                    "postAddress": postAddress,
	                    "postZip": postZip,
	                    "dutyArea": dutyArea,
	                    "dutyOfficer": dutyOfficer,
	                    "southNorthArea": southNorthArea,
	                    "belongArea": belongArea,
	                    "checkKind": checkKind,
	                    "productKind": productKind,
	                    "signOfficer": signOfficer,
	                    "repairOfficer": repairOfficer,
	                    "quotationOfficer": quotationOfficer,
	                    "operatDepartment": operatDepartment,
	                    "operator": operator,
	                    "operatDate": operatDate,
	                    "memo": memo,
	                    "state": state,
	                    "cstate": cstate,
	            };
      		}
      		jQuery(".addScaleBtn").attr("disabled", true);
      		jQuery(".saveScaleBtn").attr("disabled", true);
      		var id=isId;
      		if (id==null||id==''){
      			id = 'null';
      		}
      		if (cstate=="已完成"){
      			$.springLemonDialog({
  					content : '该合同已经生产商品计划，不能保存！',// 确认文本
  					clickButton : function(sender, modal, index) {// 按钮事件处理
  						$(this).closeDialog(modal);
  					}
      			});
  			}
      		if(cstate=="已排产"){
      			alert("保存合同后将修改排产相关信息。");
      		}
      		if (supplierCode!=''){// 验证供方合同号是否已存在
      			var urlValid=window.rootPath+"/ui/contract/validSupplierCode/"+id+"/"+supplierCode;
      	    	jQuery.ajax({
      	            url:encodeURI(urlValid),
      	            cache:false,
      	            type :"get",
      	            dataType:"json",
      	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
      	            success:function(data){
      	            	if(data.codeState==1){
      	            		message("供方合同号已存在，请修改！");
      	            		jQuery(".addScaleBtn").attr("disabled", false);
      	            		jQuery(".saveScaleBtn").attr("disabled", false);
      	            		return;
      	            	}
      	            	if (totalSum==""||totalSum==0){
      	            		message("合同总价为0，不能添加占比划分！");
      	            		jQuery(".addScaleBtn").attr("disabled", false);
      	            		jQuery(".saveScaleBtn").attr("disabled", false);
      	            		return;
      	            	}
      	            	var url0=window.rootPath+"/ui/contract/validTotalSum/"+id+"/"+totalSum+"/0";
      	         		jQuery.ajax({
      	      	            url:encodeURI(url0),
      	      	            cache:false,
      	      	            type :"get",
      	      	            dataType:"json",
      	      	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
      	      	            success:function(data){
      	      	            	if(data.sumState==1){
      	      	            		message("合同总价小于占比划分总金额，请修改！");
      	      	            		jQuery('#divideScaleModal').modal('hide');
      	      	            		jQuery(".addScaleBtn").attr("disabled", false);
      	      	            		jQuery(".saveScaleBtn").attr("disabled", false);
      	      	            		return;
      	      	            	}
	      	      	            var url = window.rootPath + "/ui/contract/saveContract";
	      	                    jQuery.ajax({
	      	                        type: 'post',
	      	                        url: url,
	      	                        data: JSON.stringify(d),
	      	                        dataType: 'json',
	      	                        contentType: 'application/json;charset=utf-8',
	      	                        success: function (data) {
	      	                        	jQuery('#contractId').val(data.contractId);
	      	                        	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
	      	                        	jQuery("#createTime").val(time);
	      	                        	jQuery(".addScaleBtn").attr("disabled", false);
	      	      	            		jQuery(".saveScaleBtn").attr("disabled", false);
	      	                        	if (state=="addScaleBtn"){
	      	                        		showDivideScaleModal();
	      	                        	} else if (state=="saveScaleBtn"){
	      	                        		saveScaleDivide();
	      	                        	}
	      	                        }
	      	                    });
      	      	            }
      	         		})
      	            }
      	    	});
      		}else{
      				if (totalSum==""||totalSum==0){
	            		message("合同总价为0，不能添加占比划分！");
	            		jQuery(".addScaleBtn").attr("disabled", false);
	            		jQuery(".saveScaleBtn").attr("disabled", false);
	            		return;
	            	}
	            	var url0=window.rootPath+"/ui/contract/validTotalSum/"+id+"/"+totalSum+"/0";
	         		jQuery.ajax({
	      	            url:encodeURI(url0),
	      	            cache:false,
	      	            type :"get",
	      	            dataType:"json",
	      	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
	      	            success:function(data){
	      	            	if(data.sumState==1){
	      	            		message("合同总价小于占比划分总金额，请修改！");
	      	            		jQuery('#divideScaleModal').modal('hide');
	      	            		jQuery(".addScaleBtn").attr("disabled", false);
	      	            		jQuery(".saveScaleBtn").attr("disabled", false);
	      	            		return;
	      	            	}
	      	            	var url = window.rootPath + "/ui/contract/saveContract";
	          	            jQuery.ajax({
	          	                type: 'post',
	          	                url: url,
	          	                data: JSON.stringify(d),
	          	                dataType: 'json',
	          	                contentType: 'application/json;charset=utf-8',
	          	                success: function (data) {
	          	                	jQuery('#contractId').val(data.contractId);
	          	                	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
	    	                        jQuery("#createTime").val(time);
	          	                	jQuery(".addScaleBtn").attr("disabled", false);
	          	            		jQuery(".saveScaleBtn").attr("disabled", false);
	    	                        if (state=="addScaleBtn"){
	    	                        	showDivideScaleModal();
	    	                       	} else if (state=="saveScaleBtn"){
      	                        		saveScaleDivide();
      	                        	}
	          	                }
	          	            });
	      	            }
	         		})
      		}
      	};
    	
    	/**
      	 * 添加占比划分时初始化弹窗
      	 */
        var showDivideScaleModal = function() {
        	jQuery('#divideScaleId').val('');
        	jQuery("#functionary").select2().val('').trigger("change");
        	jQuery('#divideScaleBelongArea').val('');
        	jQuery('#oldScaleDivide').val('');
     		jQuery('#scaleDivide').val('');
     		jQuery('#percent').val('');
     		jQuery('#divideScaleMemo').val('');
    		jQuery('#divideScaleModal').modal('show');
        }
        
        var saveScaleDivide = function() {
        	  var isId=jQuery("#divideScaleId").val();
              var contractId=jQuery("#contractId").val();
              var supplierCode=jQuery("#supplierCode").val();
              //判断是编辑还是新增
              if(isId == ""){//新增
              	var functionary = jQuery('#functionary').val();
              	var belongArea = jQuery('#divideScaleBelongArea').val();
           		var scaleDivide = jQuery('#scaleDivide').val();
           		var percent = jQuery('#percent').val();
           		var memo = jQuery('#divideScaleMemo').val();
           		var url0=window.rootPath+"/ui/contract/validTotalSum/"+contractId+"/"+scaleDivide+"/1";
           		jQuery.ajax({
        	            url:encodeURI(url0),
        	            cache:false,
        	            type :"get",
        	            dataType:"json",
        	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
        	            success:function(data){
        	            	if(data.sumState==1){
        	            		message("占比划分总金额超过合同总价，请修改占比划分金额或百分比！");
        	            		jQuery(".addScaleBtn").attr("disabled", false);
          	            		jQuery(".saveScaleBtn").attr("disabled", false);
        	            		return;
        	            	}
        	            	var api = window.rootPath + "/api/divideScales";
        	                var d = {
        	                		"contractID": contractId,
        	                        "functionary": functionary,
        	                        "belongArea": belongArea,
        	                        "scaleDivide": scaleDivide,
        	                        "percent": percent,
        	                        "memo": memo,
        	                };
        	                jQuery.ajax({
        	                    type: 'post',
        	                    url: api,
        	                    data: JSON.stringify(d),
        	                    dataType: 'json',
        	                    contentType: 'application/json;charset=utf-8',
        	                    success: function (data) {
        	                    	jQuery('#divideScaleModal').modal('hide');
        	                    	var operateType = "新增合同占比划分";
        	                    	var content = "新增【项目合同】【"+supplierCode+"】占比划分负责人【"+functionary+"】";
        	                    	addOperateLog(operateType, content);
        	                    	divideScaleData.contractId=jQuery('#contractId').val();
        	                		serverScaleTable.draw(true);
        	                		jQuery(".addScaleBtn").attr("disabled", false);
              	            		jQuery(".saveScaleBtn").attr("disabled", false);
        	                    }
        	                });
        	            }
           		})
              }
              else{//编辑
              	var functionary = jQuery('#functionary').val();
              	var belongArea = jQuery('#divideScaleBelongArea').val();
           		var oldScaleDivide = jQuery('#oldScaleDivide').val();
           		var scaleDivide = jQuery('#scaleDivide').val();
           		var percent = jQuery('#percent').val();
           		var memo = jQuery('#divideScaleMemo').val();
           		var sum = scaleDivide - oldScaleDivide;
           		var url0=window.rootPath+"/ui/contract/validTotalSum/"+contractId+"/"+sum+"/1";
           		jQuery.ajax({
        	            url:encodeURI(url0),
        	            cache:false,
        	            type :"get",
        	            dataType:"json",
        	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
        	            success:function(data){
        	            	if(data.sumState==1){
        	            		message("占比划分总金额超过合同总价，请修改占比划分金额或百分比！");
        	            		jQuery(".addScaleBtn").attr("disabled", false);
          	            		jQuery(".saveScaleBtn").attr("disabled", false);
        	            		return;
        	            	}
        	            	var url=window.rootPath+'/api/divideScales/'+isId;
        	         		var data = {
        	                        "functionary": functionary,
        	                        "belongArea": belongArea,
        	                        "scaleDivide": scaleDivide,
        	                        "percent": percent,
        	                        "memo": memo,
        	                    };
        	                 jQuery.ajax({
        	                      url:encodeURI(url),
        	                      type:'patch',
        	                      data:JSON.stringify(data),
        	                      dataType:'json',
        	                      contentType:'application/json;charset=utf-8',
        	                      success: function () {
        	                        jQuery('#divideScaleModal').modal('hide');
        	                        var operateType = "编辑合同占比划分";
        	                    	var content = "编辑【项目合同】【"+supplierCode+"】占比划分负责人【"+functionary+"】";
        	                    	addOperateLog(operateType, content);
        	                        divideScaleData.contractId=jQuery('#contractId').val();
        	                        serverScaleTable.draw(false);
        	                        jQuery(".addScaleBtn").attr("disabled", false);
              	            		jQuery(".saveScaleBtn").attr("disabled", false);
        	                      }
        	                 });
        	            }
           		})
              }
        }
    	
    	//列表中的全选
        $("#checkAllScale").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchildScale").prop("checked", check);
    	});
        
        //占比划分金额发生变化时，将其金额数换算成百分比赋给百分比
        jQuery('#scaleDivide').change(function(){
        	var scaleDivide = jQuery("#scaleDivide").val();//占比划分金额
        	if (scaleDivide==""||scaleDivide==0){
          		message("占比划分百分比不能为0！");
          		return;
          	}
        	var totalSum = jQuery('#totalSum').val();//合同总价
        	if (totalSum==""||totalSum==0){
          		message("合同总价为0，不能添加占比划分！");
          		return;
          	}
        	if (scaleDivide-totalSum>0){
          		message("占比划分金额不能大于合同总价！");
          		var percent = jQuery("#percent").val();//占比划分百分比
          		scaleDivide = percent*totalSum/100;
    			jQuery("#scaleDivide").val(scaleDivide.toFixed(2));
          		return;
          	}
        	var percent = scaleDivide*100/totalSum;
			jQuery("#percent").val(percent);
		});
        
        //百分比发生变化时，将其值换算成金额赋给占比划分金额
        jQuery('#percent').change(function(){
        	var percent = jQuery("#percent").val();//占比划分百分比
        	if (percent==""||percent==0){
          		message("占比划分百分比不能为0！");
          		return;
          	}
        	var totalSum = jQuery('#totalSum').val();//合同总价
        	if (totalSum==""||totalSum==0){
          		message("合同总价为0，不能添加占比划分！");
          		return;
          	}
        	if (percent>100){
          		message("占比划分百分比不能大于100%！");
          		var scaleDivide = jQuery("#scaleDivide").val();//占比划分金额
          		percent = scaleDivide*100/totalSum;
    			jQuery("#percent").val(percent);
          		return;
          	}
        	var scaleDivide = percent*totalSum/100;
			jQuery("#scaleDivide").val(scaleDivide.toFixed(2));
		});
    	
    });
})();